<template>
    <el-container
        class="layout-container overflow-hidden border border-gray-200"
        style="height: calc(100vh - 84px)"
    >
        <!-- 左侧分类树 -->
        <el-aside
            width="300px"
            class="aside-container border-r bg-white pl-3 pt-3 pb-3 pr-0"
        >
            <div class="flex items-center gap-3 mb-1">
                <el-icon @click="handleBack" style="cursor: pointer"
                    ><ArrowLeftBold
                /></el-icon>
                <h1 class="text-lg font-semibold">标准化建设-结算</h1>
            </div>
            <div class="flex-1 overflow-auto pr-2">
                <el-badge
                    v-for="(v, i) in getLeftList()"
                    :key="i"
                    :value="v.count"
                    class="mt-4"
                    onselectstart="return false"
                    style="cursor: pointer; width: 90%"
                >
                    <el-card shadow="hover">
                        {{ i + 1 + "、" + v.label }}</el-card
                    >
                </el-badge>
            </div>
        </el-aside>

        <!-- 右侧文件展示区 -->
        <div class="p-3 flex-1 flex flex-col">
            <div class="flex justify-between mb-1">
                <el-input
                    v-model="searchInp"
                    style="width: 300px"
                    placeholder="搜索附件名称、上传人或日期"
                    :prefix-icon="Search"
                />
                <div class="flex">
                    <el-select
                        v-model="value"
                        placeholder="全部状态"
                        style="width: 100px"
                    >
                        <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                    <el-select
                        class="mr-6 ml-6"
                        v-model="value"
                        placeholder="排序方式"
                        style="width: 100px"
                    >
                        <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                    <el-button type="primary" icon="Filter">高级筛选</el-button>
                </div>
            </div>
            <div style="flex: 1; overflow: auto">
                <el-card
                    v-for="v in categoryTreeData"
                    :key="v.id"
                    class="mt-2 mb-2"
                >
                    <template #header>
                        <div
                            class="card-header flex"
                            style="align-items: center"
                        >
                            <el-icon color="blue"><Document /></el-icon>
                            <span class="ml-1" style="font-weight: 900">{{
                                v.label
                            }}</span>
                        </div>
                    </template>

                    <el-card
                        v-for="item in v.children"
                        :key="item.id"
                        shadow="hover"
                        class="mt-1 mb-1"
                    >
                        <div class="mt-1 mb-1 flex justify-between">
                            <div class="flex" style="align-items: center">
                                <el-icon color="red" class="mr-2"
                                    ><Document
                                /></el-icon>
                                <div class="flex flex-col">
                                    <div style="font-size: 14px" class="mb-1">
                                        <span>{{ item.label }}</span>
                                        <el-tag
                                            :type="getTagColor(item.sc)"
                                            class="ml-2 mr-2"
                                            >{{ item.sc }}</el-tag
                                        >
                                        <el-tag :type="getTagColor(item.jx)">{{
                                            item.jx
                                        }}</el-tag>
                                    </div>
                                    <div
                                        class="flex"
                                        style="
                                            align-items: center;
                                            font-size: 12px;
                                        "
                                    >
                                        <el-icon><Timer /></el-icon>
                                        <span class="mr-2">{{
                                            item.date
                                        }}</span>
                                        <el-icon><User /></el-icon>
                                        <span>{{ item.name }}</span>
                                    </div>
                                </div>
                            </div>
                            <div class="icon-action-group">
                                <!-- 查看图标 -->
                                <el-tooltip content="查看" placement="top">
                                    <el-icon
                                        @click="handleView(item)"
                                        class="cursor-pointer text-gray-500 hover:text-primary"
                                    >
                                        <View />
                                    </el-icon>
                                </el-tooltip>

                                <!-- 上传图标 -->
                                <el-tooltip content="上传" placement="top">
                                    <el-icon
                                        @click="handleUpload"
                                        class="cursor-pointer text-gray-500 hover:text-primary"
                                    >
                                        <Upload />
                                    </el-icon>
                                </el-tooltip>

                                <!-- 编辑图标 -->
                                <el-tooltip content="编辑" placement="top">
                                    <el-icon
                                        @click="handleEdit"
                                        class="cursor-pointer text-gray-500 hover:text-primary"
                                    >
                                        <Edit />
                                    </el-icon>
                                </el-tooltip>

                                <!-- 统计图标 -->
                                <el-tooltip content="统计" placement="top">
                                    <el-icon
                                        @click="handleStats"
                                        class="cursor-pointer text-gray-500 hover:text-primary"
                                    >
                                        <Histogram />
                                    </el-icon>
                                </el-tooltip>

                                <!-- 删除图标 -->
                                <el-tooltip content="删除" placement="top">
                                    <el-icon
                                        @click="handleDelete"
                                        class="cursor-pointer text-gray-500 hover:text-danger"
                                    >
                                        <Delete />
                                    </el-icon>
                                </el-tooltip>
                            </div>
                        </div>
                    </el-card>
                </el-card>
            </div>
        </div>
        <!-- 上传文件模态框 -->
        <el-dialog v-model="showUploadDialog" title="上传文件" width="500px">
            <el-upload
                class="upload-demo"
                drag
                action="#"
                :on-change="handleFileChange"
                :on-remove="handleFileRemove"
                :file-list="uploadFiles"
                :auto-upload="false"
                accept=".pdf,.doc,.docx,.xls,.xlsx,.zip"
            >
                <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                <div class="el-upload__text">
                    拖拽文件至此处或<em>点击上传</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip text-sm text-gray-500 mt-2">
                        支持上传 PDF、Word、Excel、ZIP 格式文件，单个文件不超过
                        50MB
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <el-button @click="showUploadDialog = false">取消</el-button>
                <el-button type="primary" @click="confirmUpload"
                    >确认上传</el-button
                >
            </template>
        </el-dialog>
    </el-container>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, nextTick } from "vue";
import {
    Folder,
    FolderOpened,
    Document,
    UploadFilled,
    Refresh,
    Search,
    Upload,
    Download,
    View,
    Edit,
    Delete,
    Histogram,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();

// 1. 树形分类数据
const categoryTreeData = ref([
    {
        id: "1",
        label: "结算核心文件",
        fileCount: 5,
        children: [
            {
                id: "1-1",
                label: "结算书封皮",
                fileCount: 2,
                date: "2023-09-05",
                sc: "已上传",
                jx: "已解析",
                name: "张工程师",
                count: 2,
            },
            {
                id: "1-2",
                label: "结算汇总表",
                fileCount: 3,
                date: "2023-09-07",
                sc: "已上传",
                jx: "解析中",
                name: "张工程师",
                count: 4,
            },
            {
                id: "1-3",
                label: "工程结算书",
                fileCount: 0,
                date: "2023-09-09",
                sc: "已上传",
                jx: "已解析",
                name: "张工程师",
                count: 5,
            },
        ],
    },
    {
        id: "2",
        label: "工程量相关",
        fileCount: 7,
        children: [
            {
                id: "2-1",
                label: "工程量计算表",
                fileCount: 4,
                date: "2023-09-07",
                sc: "已上传",
                jx: "已解析",
                name: "李造价",
                count: 2,
            },
            {
                id: "2-2",
                label: "工程量确认单",
                fileCount: 3,
                date: "2023-09-07",
                sc: "已上传",
                jx: "已解析",
                name: "李造价",
                count: 2,
            },
        ],
    },
    {
        id: "3",
        label: "合同与招投标",
        fileCount: 12,
        children: [
            {
                id: "3-1",
                label: "承包合同",
                fileCount: 2,
                date: "2023-09-07",
                sc: "已上传",
                jx: "已解析",
                name: "李造价",
                count: 12,
            },
            {
                id: "3-2",
                label: "中标通知书",
                fileCount: 1,
                date: "2023-09-07",
                sc: "已上传",
                jx: "已解析",
                name: "李造价",
                count: 11,
            },
            {
                id: "3-3",
                label: "招标文件、投标文件",
                fileCount: 6,
                date: "2023-09-07",
                sc: "已上传",
                jx: "已解析",
                name: "李造价",
                count: 15,
            },
            {
                id: "3-4",
                label: "谈判文件、谈判响应文件",
                fileCount: 3,
                date: "2023-09-07",
                sc: "已上传",
                jx: "已解析",
                name: "李造价",
                count: 12,
            },
        ],
    },
    {
        id: "4",
        label: "工程验收文件",
        fileCount: 4,
        children: [
            {
                id: "4-1",
                label: "竣工结算通知书",
                fileCount: 1,
                date: "2023-09-07",
                sc: "已上传",
                jx: "已解析",
                name: "李造价",
                count: 14,
            },
            {
                id: "4-2",
                label: "开工报告、竣工验收报告",
                fileCount: 3,
                date: "2023-09-07",
                sc: "已上传",
                jx: "已解析",
                name: "李造价",
                count: 15,
            },
        ],
    },
    {
        id: "5",
        label: "图纸资料",
        fileCount: 8,
        children: [
            {
                id: "5-1",
                label: "施工图纸及变更",
                fileCount: 5,
                date: "2023-09-07",
                sc: "未上传",
                jx: "已解析",
                name: "李造价",
                count: 16,
            },
            {
                id: "5-2",
                label: "竣工图",
                fileCount: 3,
                date: "2023-09-07",
                sc: "已上传",
                jx: "已解析",
                name: "李造价",
                count: 0,
            },
        ],
    },
    {
        id: "6",
        label: "其他资料",
        fileCount: 10,
        children: [
            {
                id: "6-1",
                label: "甲供物资领用单",
                fileCount: 2,
                date: "2023-09-07",
                sc: "已上传",
                jx: "已解析",
                name: "李造价",
                count: 0,
            },
            {
                id: "6-2",
                label: "水电表确认表",
                fileCount: 1,
                date: "2023-09-07",
                sc: "已上传",
                jx: "已解析",
                name: "李造价",
                count: 2,
            },
            {
                id: "6-3",
                label: "技术部门出具的合同考核扣款清单",
                fileCount: 1,
                date: "2023-09-07",
                sc: "已上传",
                jx: "已解析",
                name: "李造价",
                count: 4,
            },
            {
                id: "6-4",
                label: "隐蔽工程检查资料",
                fileCount: 3,
                date: "2023-09-07",
                sc: "已上传",
                jx: "已解析",
                name: "李造价",
                count: 0,
            },
            {
                id: "6-5",
                label: "概算批复文件及概算批准表",
                fileCount: 3,
                date: "2023-09-07",
                sc: "已上传",
                jx: "已解析",
                name: "李造价",
                count: 9,
            },
        ],
    },
]);

// 3. 当前选中的分类
const currentCategory = ref(null);

// 4. 文件数据存储
const fileData = reactive({
    "1-1": [
        {
            id: "1-1-1",
            name: "结算书封皮模板.pdf",
            status: "已上传",
            size: "2.4MB",
            uploader: "张工程师",
            date: "2023-09-01",
        },
        {
            id: "1-1-2",
            name: "结算书封皮示例.pdf",
            status: "已上传",
            size: "1.8MB",
            uploader: "李工程师",
            date: "2023-09-02",
        },
    ],
    "1-2": [
        {
            id: "1-2-1",
            name: "结算汇总表2023.xlsx",
            status: "已上传",
            size: "3.2MB",
            uploader: "王工程师",
            date: "2023-09-03",
        },
        {
            id: "1-2-2",
            name: "结算汇总表历史数据.xlsx",
            status: "已上传",
            size: "5.6MB",
            uploader: "赵工程师",
            date: "2023-09-04",
        },
        {
            id: "1-2-3",
            name: "季度结算汇总对比表.xlsx",
            status: "已上传",
            size: "2.1MB",
            uploader: "张工程师",
            date: "2023-09-05",
        },
    ],
    "2-1": [
        {
            id: "2-1-1",
            name: "主体结构工程量计算表.xlsx",
            status: "已上传",
            size: "2.8MB",
            uploader: "李工程师",
            date: "2023-09-06",
        },
        {
            id: "2-1-2",
            name: "二次结构工程量计算表.xlsx",
            status: "已上传",
            size: "1.9MB",
            uploader: "王工程师",
            date: "2023-09-07",
        },
        {
            id: "2-1-3",
            name: "装饰工程量计算表.xlsx",
            status: "已上传",
            size: "3.5MB",
            uploader: "赵工程师",
            date: "2023-09-08",
        },
        {
            id: "2-1-4",
            name: "安装工程量计算表.xlsx",
            status: "已上传",
            size: "4.2MB",
            uploader: "张工程师",
            date: "2023-09-09",
        },
    ],
    "2-2": [
        {
            id: "2-2-1",
            name: "土建部分工程量确认单.pdf",
            status: "已上传",
            size: "1.2MB",
            uploader: "李工程师",
            date: "2023-09-10",
        },
        {
            id: "2-2-2",
            name: "安装部分工程量确认单.pdf",
            status: "已上传",
            size: "1.5MB",
            uploader: "王工程师",
            date: "2023-09-11",
        },
        {
            id: "2-2-3",
            name: "室外工程工程量确认单.pdf",
            status: "已上传",
            size: "0.9MB",
            uploader: "赵工程师",
            date: "2023-09-12",
        },
    ],
});

// 5. 当前分类的文件列表
const currentFiles = ref([]);

// 6. 搜索和分页相关
const searchInp = ref("");

const value = ref("");

const options = [
    {
        value: "Option1",
        label: "Option1",
    },
    {
        value: "Option2",
        label: "Option2",
    },
    {
        value: "Option3",
        label: "Option3",
    },
    {
        value: "Option4",
        label: "Option4",
    },
    {
        value: "Option5",
        label: "Option5",
    },
];
// 7. 上传文件相关
const showUploadDialog = ref(false);
const uploadFiles = ref([]);

// 按钮事件（可根据实际需求扩展）
const handleBack = () => {
    ElMessage.info("返回上一页");
    router.back();
    // 实际项目中可使用vue-router的back()
};
const getTagColor = (str) => {
    switch (str) {
        case "已上传":
            return "primary";
            break;
        case "未上传":
            return "success";
            break;
        case "已解析":
            return "danger";
            break;
        case "解析中":
            return "warning";
            break;

        default:
            break;
    }
};

const getLeftList = () => {
    let arr = [];
    for (let index = 0; index < categoryTreeData.value.length; index++) {
        const element = categoryTreeData.value[index];
        for (let i = 0; i < element.children.length; i++) {
            const item = element.children[i];
            arr.push(item);
        }
    }

    return arr;
};

// 查看文件
const handleView = (item) => {
    console.log(item);
    router.push({
        path: "/settMgmt/fileCompilationDetails",
        query: item,
    });
    // ElMessage.info(`正在查看文件：${file.name}`);
};

// 编辑文件
const handleEdit = (file) => {
    ElMessage.info(`正在编辑文件：${file.name}`);
};

// 删除文件
const handleDelete = (file) => {
    ElMessageBox.confirm(
        `确定要删除文件"${file.name}"吗？此操作不可恢复。`,
        "确认删除",
        {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }
    )
        .then(() => {
            const index = currentFiles.value.findIndex((f) => f.id === file.id);
            if (index !== -1) {
                currentFiles.value.splice(index, 1);
                fileData[currentCategory.value.id] = [...currentFiles.value];
                updateFileCount(currentCategory.value.id, -1);
                ElMessage.success("文件已删除");
            }
        })
        .catch(() => {
            // 取消删除
        });
};

// 打开上传对话框
const handleUpload = () => {
    if (!currentCategory.value) {
        ElMessage.warning("请先选择文件分类");
        return;
    }
    uploadFiles.value = [];
    showUploadDialog.value = true;
};

// 处理文件上传变化
const handleFileChange = (file, fileList) => {
    uploadFiles.value = fileList;
};

// 处理文件移除
const handleFileRemove = (file, fileList) => {
    uploadFiles.value = fileList;
};

// 确认上传
const confirmUpload = () => {
    if (uploadFiles.value.length === 0) {
        ElMessage.warning("请选择要上传的文件");
        return;
    }

    ElMessage.loading("文件上传中，请稍候...", { duration: 0 });

    setTimeout(() => {
        const newFiles = uploadFiles.value.map((file) => ({
            id: `${currentCategory.value.id}-${Date.now()}-${Math.random()
                .toString(36)
                .substr(2, 5)}`,
            name: file.name,
            status: "已上传",
            size: formatFileSize(file.size),
            uploader: "当前用户",
            date: new Date().toLocaleDateString(),
        }));

        currentFiles.value = [...currentFiles.value, ...newFiles];
        fileData[currentCategory.value.id] = [...currentFiles.value];
        updateFileCount(currentCategory.value.id, newFiles.length);

        showUploadDialog.value = false;
        ElMessage.success(`成功上传${newFiles.length}个文件`);
    }, 1500);
};

// 更新文件数量
const updateFileCount = (id, change) => {
    const updateNode = (nodes) => {
        for (const node of nodes) {
            if (node.id === id) {
                node.fileCount = (node.fileCount || 0) + change;
                return true;
            }
            if (node.children && node.children.length) {
                if (updateNode(node.children)) {
                    node.fileCount = (node.fileCount || 0) + change;
                    return true;
                }
            }
        }
        return false;
    };

    updateNode(categoryTreeData.value);
};

// 格式化文件大小
const formatFileSize = (bytes) => {
    if (bytes === 0) return "0 Bytes";
    const k = 1024;
    const sizes = ["Bytes", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

// 页面初始化
onMounted(() => {
    const firstLeafNode = findFirstLeafNode(categoryTreeData.value);
    if (firstLeafNode) {
        currentCategory.value = firstLeafNode;
        currentFiles.value = fileData[firstLeafNode.id] || [];

        const tree = document.querySelector(`[data-key="${firstLeafNode.id}"]`);
        if (tree) {
            tree.click();
        }
    }
});

// 查找第一个叶子节点
const findFirstLeafNode = (nodes) => {
    for (const node of nodes) {
        if (!node.children || node.children.length === 0) {
            return node;
        }
        const leaf = findFirstLeafNode(node.children);
        if (leaf) return leaf;
    }
    return null;
};

// 统计操作
const handleStats = () => {
    ElMessage.info("执行「统计」操作");
};
</script>

<style scoped>
/* 响应式适配 */
@media (max-width: 768px) {
    .aside-container {
        width: 200px !important;
    }

    .operation-group {
        width: 100%;
        flex-wrap: wrap;
    }

    .el-input {
        width: 100% !important;
    }
}
.icon-action-group {
    display: flex;
    gap: 16px; /* 图标间距 */
    align-items: center;
}

.el-icon {
    font-size: 18px; /* 图标大小 */
    transition: color 0.2s; /*  hover 过渡效果 */
}
::v-deep .aside-container .el-card__body {
    padding: 0 5px !important;
}
.el-aside {
    display: flex;
    flex-direction: column;
    margin-bottom: 0;
}
</style>
